package com.ssm.blog.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.blog.pojo.Message;
import com.ssm.blog.pojo.User;
import com.ssm.blog.service.MessageService;
import com.ssm.blog.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @RequestMapping("add.html")
    @ResponseBody
    public Map<String, Object> add(Message message, HttpSession session) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        Map<String, Object> result = new HashMap<>();
        if (user == null) {
            result.put("status", false);
            result.put("login", false);
        } else {
            message.setUser(user);
            message.setCreatedDate(new Date());
            messageService.addMessage(message);
            result.put("status", true);
            result.put("message", message);
        }
        return result;
    }

    @RequestMapping("list.html")
    public ModelAndView list(@RequestParam(defaultValue = "1") Integer pageNum) {
        PageInfo<Message> messages = messageService.getMessageList(pageNum);
        return new ModelAndView("message_board", "messages", messages);
    }
}
